package ctxSemanticsGen;

import java.io.*;
import java.util.ArrayList;

import javax.xml.parsers.*;
import org.w3c.dom.*;


/**
 * Wrapper for an xml COP description file .
 * 
 * @author guido
 *
 */
public class XmlProjectAnalyzer {

	public static final String LAYERED_CLASS_TAG = "LayeredClass";
	public static final String LAYER_TAG = "Layer";
	
	ArrayList<String> layeredClasses = new ArrayList<String>();
	ArrayList<String> layers = new ArrayList<String>();

	String xmlCopFileWithPath;
	
	
	/**
	 * Creates a descriptor from an xml file. The constructor 
	 * reads the file and initializes the proper data structures.
	 * Call like: ProjectAnalyzer"../TestCOPMethSynt/COPdescriptor.xml"
	 * 
	 * @param xmlCopFileWithPath
	 */
	public XmlProjectAnalyzer(String xmlCopFileWithPath) {
		this.xmlCopFileWithPath = xmlCopFileWithPath;
		this.run();
	}
	
	
	/**
	 * Gives the layered classes declared in the xml file
	 * 
	 * @return
	 */
	public ArrayList<String> getLayeredClasses(){
		return layeredClasses;
	}
	
	
	/**
	 * Gives the layers declared in the xml file
	 * 
	 * @return
	 */
	public ArrayList<String> getLayers(){
		return layers;
	}
	
	
	/*
	 * Read the file and extract the information
	 */
	private void run() {
		try {
			File file = new File(xmlCopFileWithPath);
			if (!file.exists()) {
				throw new RuntimeException("xml COP file not found!");
			}
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlCopFileWithPath);

			// Get a list of the LAYERED_CLASS_TAG elements
			NodeList list = doc.getElementsByTagName(LAYERED_CLASS_TAG);
			for (int i = 0; i < list.getLength(); i++) {
				Element element = (Element) list.item(i);
				// TODO: make this more robust
				String s = element.getChildNodes().item(0).getTextContent();
				layeredClasses.add(s.trim());
			}
			
			// Get a list of the LAYER_TAG elements
			NodeList list1 = doc.getElementsByTagName(LAYER_TAG);
			for (int i = 0; i < list1.getLength(); i++) {
				Element element = (Element) list1.item(i);
				// TODO: make this more robust
				String s = element.getChildNodes().item(0).getTextContent();
				layers.add(s.trim());
			}
			
		} catch (Exception e) { throw new RuntimeException(e); }
	}

	
	// Test
	static public void main(String[] arg) {
		XmlProjectAnalyzer xpa = 
			new XmlProjectAnalyzer("../TestCOPMethSynt/COPdescriptor.xml");
		for(String s : xpa.getLayeredClasses()){
			System.out.println(s);
	    }
		for(String s : xpa.getLayers()){
			System.out.println(s);
	    }
	}
}





